﻿#region << 文件说明 >>
/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.SocketCore.Extensions
 * 唯一标识：4194c78c-63d5-4c85-a0bb-5820107ed220
 * 文件名：DictionaryExtension
 * 
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2024/8/12 21:01:44
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 文件说明 >>

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Vampirewal.Core.SocketCore.Extensions;

/// <summary>
/// 
/// </summary>
public static class DictionaryExtension
{
    /// <summary>
    /// 移除满足条件的项目。
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="pairs"></param>
    /// <param name="func"></param>
    /// <returns></returns>
    public static int RemoveWhen<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> pairs, Func<KeyValuePair<TKey, TValue>, bool> func)
    {
        var list = new List<TKey>();
        foreach (var item in pairs)
        {
            if (func?.Invoke(item) == true)
            {
                list.Add(item.Key);
            }
        }

        var count = 0;
        foreach (var item in list)
        {
            if (pairs.TryRemove(item, out _))
            {
                count++;
            }
        }
        return count;
    }


    /// <summary>
    /// 尝试添加
    /// </summary>
    /// <typeparam name="Tkey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="dictionary"></param>
    /// <param name="tkey"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static void AddOrUpdate<Tkey, TValue>(this ConcurrentDictionary<Tkey, TValue> dictionary, Tkey tkey, TValue value)
    {
        if (dictionary.ContainsKey(tkey))
        {
            dictionary[tkey] = value;
        }
        else
        {
            dictionary.TryAdd(tkey, value);
        }
    }

}